package com.thfw.test.view.mq;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.Serializable;

/**
 * Created by scooper_lxx on 2017/2/16.
 */

public class MessageModel extends  JSONObject implements Serializable {

    private int id;
    private String type;
    private Object data;
    private String source;

    public MessageModel(int id, String type, Object data, String source) {
        this.id = id;
        this.type = type;
        this.data = data;
        this.source = source;
    }

    public MessageModel(int id, String type, Object data) {
        this.id = id;
        this.type = type;
        this.data = data;
        this.source = "";
    }

    public int getId() {
        return this.id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getType() {
        return this.type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Object getData() {
        return this.data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public String getSource() {
        return this.source;
    }

    public void setSource(String source) {
        this.source = source;
    }

    public static JSONObject changeStringToJson(String message) throws JSONException {
        JSONTokener jsonTokener = new JSONTokener(message);
        return message == null?null: (JSONObject) jsonTokener.nextValue();
    }

    public static MessageModel changeStringToModel(String message) throws JSONException {
        JSONObject jsonobject = changeStringToJson(message);
        if(jsonobject != null) {
            MessageModel cometdMessage = new MessageModel(jsonobject.getInt("id"), jsonobject.getString("type"), jsonobject.get("data"), jsonobject.getString("source"));
            return cometdMessage;
        } else {
            return null;
        }
    }

    @Override
    public String toString() {
        return "{" +
                "\"id\":"+"\"" + id +"\" ," +
                "\"type\":"+"\"" + type +"\" ," +
                "\"data\":" + data +","+
                "\"source\":"+"\"" + source +"\"" +
                '}';
    }
}
